package com.example.longimageView.view;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import java.io.File;
import java.io.InputStream;

/**
 * @auth: njb
 * @date: 2022/11/7 0:08
 * @desc:
 */
public class LongImageView extends AppCompatImageView {
    private String TAG = getClass().getSimpleName();
    private int mTargetY = 0;
    private int scrollDistance = 0;
    private int imgWidth = 0, imgHeight = 0;
    private Bitmap imgBitmap = null;
    private Bitmap holderBitmap;
    private BitmapRegionDecoder bitmapRegionDecoder;
    private boolean isScrolling = false;
    private float startY = -1;
    private int mStartTargetY = -1;
    private BitmapFactory.Options scaleOptions = new BitmapFactory.Options();
    public Bitmap bitmap;
    public static final String EVENT_PROP_URL = "url";
    public static final String EVENT_PROP_BITMAP_WIDTH = "resourceWidth";
    public static final String EVENT_PROP_BITMAP_HEIGHT = "resourceHeight";

    public LongImageView(Context context) {
        super(context);
        init();
    }

    public LongImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LongImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //遥控器按键事件
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                scrollDistance = scrollDistance <= 0 ? getHeight() : scrollDistance;
                if (event.getAction() == KeyEvent.ACTION_DOWN && !isScrolling) {
                    switch (event.getKeyCode()) {
                        case KeyEvent.KEYCODE_DPAD_UP:
                            scrollBy(0 - viewHeight2ImageHeight(scrollDistance));
                            break;
                        case KeyEvent.KEYCODE_DPAD_DOWN:
                            scrollBy(viewHeight2ImageHeight(scrollDistance));
                            break;
                    }
                }
                return false;
            }

        });
        //响应鼠标拖拽(手指也可以)
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e(TAG, " touch down");
                        startY = event.getRawY();
                        mStartTargetY = mTargetY;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float currentY = event.getRawY();
                        mTargetY = mStartTargetY + (int) (viewHeight2ImageHeight((int) (startY - currentY)) * 1f);
                        mTargetY = Math.max(0, Math.min(mTargetY, imgHeight - viewHeight2ImageHeight(getHeight())));
                        Log.e(TAG, " touch move " + mTargetY);
                        invalidate();
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e(TAG, " touch up");
                        startY = -1;
                        break;
                }
                return true;
            }
        });
    }

    private void startScroll(int targetY) {
        targetY = Math.max(0, Math.min(targetY, imgHeight - viewHeight2ImageHeight(getHeight())));
        ValueAnimator valueAnimator = ValueAnimator.ofInt(mTargetY, targetY);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mTargetY = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isScrolling = true;
            }

            @Override

            public void onAnimationEnd(Animator animation) {
                isScrolling = false;
            }

            @Override

            public void onAnimationCancel(Animator animation) {
                isScrolling = false;
            }

            @Override

            public void onAnimationRepeat(Animator animation) {
            }
        });
        valueAnimator.setInterpolator(new LinearInterpolator());
        //设置滑动速度
        valueAnimator.setDuration(10);
        valueAnimator.start();
    }


    /**
     * 根据InputStream 生成 BitmapRegionDecoder
     *
     * @param imgStream
     */
    public void setImageStream(InputStream imgStream) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(imgStream, new Rect(0, 0, 0, 0), options);
            imgWidth = options.outWidth;
            imgHeight = options.outHeight;
            //寻找最佳的缩放比例
            int viewHeight2ImageHeight = viewHeight2ImageHeight(getHeight());
            //设置缩放比例
            int scale = getScaleValue(imgWidth, viewHeight2ImageHeight, 0);
            scaleOptions.inSampleSize = scale;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            bitmapRegionDecoder = BitmapRegionDecoder.newInstance(imgStream, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据图片文件 生成 BitmapRegionDecoder
     *
     * @param imgFile
     */
    public void setImageFile(File imgFile) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
            imgWidth = options.outWidth;
            imgHeight = options.outHeight;
            //寻找最佳的缩放比例
            int viewHeight2ImageHeight = viewHeight2ImageHeight(getHeight());
            int scale = getScaleValue(imgWidth, viewHeight2ImageHeight, 0);
            scaleOptions.inSampleSize = scale;
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            bitmapRegionDecoder = BitmapRegionDecoder.newInstance(imgFile.getAbsolutePath(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int getScaleValue(int imgWidth, int imgHeight, int scaleValue) {
        long memory = Runtime.getRuntime().maxMemory() / 2;
        if (memory > 0) {
            if (imgWidth * imgHeight * 4 > memory) {
                scaleValue += 1;
                return getScaleValue(imgWidth, imgHeight, scaleValue);
            }
        }
        return scaleValue;
    }

    /**
     * 根据图片Id 生成 BitmapRegionDecoder
     *
     * @param resourceId
     */
    @SuppressLint("ResourceType")
    public void setImageResource(int resourceId) {
        InputStream imgStream = getResources().openRawResource(resourceId);
        setImageStream(imgStream);
    }

    /**
     * 设置占位图
     *
     * @param holderId
     */
    public void setPlaceHolder(int holderId) {
        holderBitmap = BitmapFactory.decodeResource(getResources(), holderId);
    }

    /**
     * 滑动到具体的位置
     *
     * @param targetY
     */
    private void scrollTo(int targetY) {
        startScroll(targetY);
    }

    /**
     * 设置相对于当前，继续滑动的距离。小于0 向上滑动，大于0向下滑动
     *
     * @param distance
     */
    private void scrollBy(int distance) {
        startScroll(mTargetY + distance);
    }

    /**
     * 设置每次滑动的距离
     *
     * @param scrollDistance
     */
    public void setScrollDistance(int scrollDistance) {
        this.scrollDistance = scrollDistance;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.e(getClass().getSimpleName(), "draw start " + getWidth() + " " + getHeight());
        canvas.save();
        int sr = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        if (bitmapRegionDecoder != null) {
            int targetHeight = viewHeight2ImageHeight(getHeight());//根据控件的高度获取需要在原始图片上截取的高度
            Log.e(getClass().getSimpleName(), "targetHeight " + targetHeight);
            Log.e(getClass().getSimpleName(), "draw resource "
                    + " " + imgWidth + " " + imgHeight
                    + " " + mTargetY + " " + targetHeight);
            imgBitmap = null;
            if (imgHeight - mTargetY >= targetHeight) {//剩余区域大于 当前控件高度
                imgBitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, mTargetY, imgWidth, mTargetY + targetHeight)
                        , scaleOptions);
            } else {//剩余区域小于 当前控件高度
                imgBitmap = bitmapRegionDecoder.decodeRegion(new Rect(0, imgHeight - targetHeight, imgWidth, imgHeight)
                        , scaleOptions);
            }
            if (imgBitmap != null) {
                //绘制需要展示的图片
                canvas.drawBitmap(imgBitmap
                        , new Rect(0, 0, imgBitmap.getWidth(), imgBitmap.getHeight())
                        , new Rect(0, 0, getWidth(), getHeight())
                        , paint);
            }
            imgBitmap = null;
            holderBitmap = null;
        } else {
            if (holderBitmap != null) {//绘制占位图
                canvas.drawBitmap(holderBitmap
                        , new Rect(0, 0, holderBitmap.getWidth(), holderBitmap.getHeight())
                        , new Rect(0, 0, getWidth(), getHeight())
                        , paint);
            }
        }
        canvas.restoreToCount(sr);
        canvas.restore();
        Log.e(getClass().getSimpleName(), "draw end");
    }

    /**
     * 图片高度转为相对于控件的高度
     *
     * @param imgHeight
     * @return
     */
    private int imageHeight2ViewHeight(int imgHeight) {
        if (this.imgHeight <= 0) {
            return 0;
        }
        return (int) (imgHeight / ((float) getWidth() / imgWidth * imgHeight) * getHeight());
    }

    /**
     * 控件高度转为相对于图片高度
     *
     * @param viewHeight
     * @return
     */
    private int viewHeight2ImageHeight(int viewHeight) {
        if (getHeight() <= 0) {
            return 0;
        }
        return (int) (viewHeight / ((float) getWidth() / imgWidth * imgHeight) * imgHeight);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        release();
    }

    public void release() {
        if (imgBitmap != null && !imgBitmap.isRecycled()) {
            imgBitmap.recycle();
            imgBitmap = null;
        }
        if (holderBitmap != null && !holderBitmap.isRecycled()) {
            holderBitmap.recycle();
            holderBitmap = null;
        }
        System.gc();
    }
}
